package mx.com.fractal.ristorante.rest;

import javax.ejb.EJB;
import javax.ejb.Singleton;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import mx.com.fractal.ristorante.dto.ErrorResponseDTO;
import mx.com.fractal.ristorante.dto.MesaDTO;
import mx.com.fractal.ristorante.exception.ObjectAlreadyExistException;
import mx.com.fractal.ristorante.service.MesaService;

import org.apache.log4j.Logger;
import org.jboss.resteasy.annotations.providers.jaxb.json.BadgerFish;

@Singleton
@Path("mesa")
public class MesaRest {
	
	@EJB
	private MesaService mesaService;
	private static final Logger logger = Logger.getLogger(MesaRest.class);

	@PUT
	@Path("save/{idRestaurante}/{numMesa}") @BadgerFish
	@Produces(value={MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON})
	public Response save(@PathParam("idRestaurante") Short idRestaurante,
			@PathParam("numMesa") Short numMesa){
		
		MesaDTO mesa=new MesaDTO();
		mesa.setNumMesa(numMesa);
		mesa.setIdRestaurante(idRestaurante);
		try {
			mesaService.save(mesa);
			return Response.ok(mesa).build();
		}catch(ObjectAlreadyExistException e){
			logger.warn("Objecto duplicado en BD", e);
			ErrorResponseDTO error=new ErrorResponseDTO();
			error.setMensaje(e.getMessage());
//			412
			return Response.status(Status.PRECONDITION_FAILED).entity(error).build();
		} catch (Exception e) {
			ErrorResponseDTO error=new ErrorResponseDTO();
			error.setMensaje(e.getMessage());
			return Response.serverError().entity(error).build();
		}
		
	}
}
